package com.dongdongshop.service.impl;

import cn.hutool.core.lang.hash.Hash;
import cn.hutool.core.util.RandomUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dongdongshop.service.SendSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SendSmsServiceImpl implements SendSmsService {

    @Autowired
    private Client client;

    @Value("${sendSms.signName}")
    private String sendSms;

    @Value("${sendSms.templateCode}")
    private String templateCode;

    @Autowired
    private StringRedisTemplate redisTemplate;

    //发送短信
    @Override
    public void sendMessages(String phone) {
        String code = RandomUtil.randomNumbers(4);

        ValueOperations<String, String> str = redisTemplate.opsForValue();
        str.set(phone,code,5,TimeUnit.MINUTES);

        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName(sendSms)
                .setTemplateCode(templateCode)
                .setTemplateParam("{\"sms_code\":\""+code+"\"}");
        RuntimeOptions runtime =new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

    }
}
